package com.xr.blackhoole.mock;


import com.xr.blackhoole.mock.annotation.WormholeMock;
import com.xr.blackhoole.mvc.utils.WormholeCommonUtils;

import java.util.Random;

public abstract class AbstractWormholeMockCallback implements WormholeMockCallback {


    private Random random = new Random();


    private Boolean[] probabilityPool = null;
    /**
     * 最小延时
     */
    private long minDelayTime;
    /**
     * 最大延时
     */
    private long maxDelayTime;

    public void init(WormholeMock wormholeMock) {
        if (null != wormholeMock) {
            initProbabilityPool(wormholeMock.passRate());
            initDelayTime(wormholeMock);
        }
    }

    /**
     * 初始化延时时间
     *
     * @param wormholeMock
     */
    private void initDelayTime(WormholeMock wormholeMock) {
        minDelayTime = getMinDelayTime() == -1 ? wormholeMock.minDelayTime() : getMinDelayTime();
        maxDelayTime = getMaxDelayTime() == -1 ? wormholeMock.maxDelayTime() : getMaxDelayTime();
    }

    /**
     * 初始化成功率池
     *
     * @param passRate
     */
    private void initProbabilityPool(byte passRate) {
        passRate = passRate < 0 ? 0 : passRate;
        passRate = passRate > 100 ? 100 : passRate;
        if (passRate >= 0 && passRate <= 100) {
            probabilityPool = new Boolean[100];
            for (byte i = 0; i < 100; i++) {
                if (passRate > i) {
                    probabilityPool[i] = true;
                } else {
                    probabilityPool[i] = false;
                }
            }
            probabilityPool = WormholeCommonUtils.shuffle(probabilityPool);
        }
    }

    public Object handelMockData(Object[] parameter) {
        boolean verifyStatus = false;
        if (null != probabilityPool) {
            int pointe = random.nextInt(probabilityPool.length);
            verifyStatus = probabilityPool[pointe];
        } else {
            verifyStatus = verify(parameter);
        }
        //进行延时
        long delayTime = getDelayTime(verifyStatus);
        //  logger.debug("invok mack method verify:[{}] - delayTime:[{}]", verifyStatus, delayTime);
        WormholeCommonUtils.delay(delayTime);
        if (verifyStatus) {
            return success(parameter);
        } else {
            return fail(parameter);
        }

    }

    /**
     * 延时
     *
     * @param verifyStatus
     */

    /**
     * 获取延时时长
     *
     * @param verifyStatus
     * @return
     */
    public long getDelayTime(boolean verifyStatus) {
        return (long) (Math.random() * (maxDelayTime - minDelayTime) + minDelayTime);
    }


    public boolean verify(Object[] parameter) {
        return false;
    }


    public long getMinDelayTime() {
        return -1;
    }

    public long getMaxDelayTime() {
        return -1;
    }
}
